package com.example.service.impl;

import com.example.entity.Role;
import com.example.entity.User;
import com.example.mapper.StudentMapper;
import com.example.mapper.TeacherMapper;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("UserService")
public class UserServiceImpl implements UserService, UserDetailsService {

    @Resource
    UserMapper userMapper;
    @Resource
    StudentMapper studentMapper;
    @Resource
    TeacherMapper teacherMapper;

    @Override
    public Integer UpdateLoginTime(String num, String loginTime, Boolean isStu) {
        if (isStu) return studentMapper.updateLoginTime(loginTime,num);
        else return teacherMapper.updateLoginTime(loginTime,num);
    }

    @Override
    public Integer UpdateUserPassword(String num, String password,Boolean isStu) {
        if(isStu) return studentMapper.updatePassword(num,password);
        else return teacherMapper.updatePassword(num,password);
    }

    @Override
    public String getUserPassword(String num, Boolean isStu) {
        if(isStu) return studentMapper.getSPassword(num);
        else return teacherMapper.getTPassword(num);
    }

    @Override
    public Role JudgeRole(String num) {
        Role role = new Role();
        int role_id=userMapper.GetRoleId(num);
        role.setROLE_id(role_id);
        role.setROLE_name(userMapper.GerRoleName(role_id));
        return role;
    }

    @Override
    public Boolean IsFirstLogin(String num, Boolean isStu) {

        if(isStu){
            return studentMapper.getSLoginTime(num) == null;
        }else{
            return teacherMapper.getTLoginTime(num) == null;
        }
    }

    @Override
    public User DoLogin(String num) {
        //判断权限
        Role role =JudgeRole(num);
        User user = null;
        if(role.getROLE_id()==1 || role.getROLE_id()==0){   //教师 或管理员
            user = userMapper.DoTLogin(num);
            user.setRole(role);
        }else if(role.getROLE_id()==2){ //学生
            user = userMapper.DoSLogin(num);
            user.setRole(role);
        }
        return user;
    }

    @Override
    public Integer ImportUsers(List<User> userList) {
        return userMapper.ImportUsers(userList);
    }

    @Override
    public UserDetails loadUserByUsername(String num) throws UsernameNotFoundException {
        User user = DoLogin(num);
        if(user==null){
            throw new UsernameNotFoundException("该用户不存在！");
        }

        return new org.springframework.security.core.userdetails.User(user.getNum(),
               user.getPassword()  ,user.getAuthorities());
    }
}
